package com.yc.navy.goods.filter;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import com.yc.navy.goods.exception.RateLimiterException;

@Component
public class RateLimiterFilter extends ZuulFilter{
	private static final RateLimiter RATE_LIMIETER = RateLimiter.create(400);
	/**
	 * 执行过滤器前要做的事情，如果返回false,则请求到此结束
	 */
	@Override
	public boolean shouldFilter() {
		return true;
	}
	
	/**
	 * 如果shouldFilter() 返回为true,这个方法才会执行
	 */
	@Override
	public Object run() throws ZuulException {
		if(!RATE_LIMIETER.tryAcquire()) {//说明没有拿到值
			throw new RateLimiterException();
		}
		return null;
	}
	
	/**
	 * 指定过滤类型
	 */
	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}
	
	/**
	 * 过滤器的优先级，值越小优先级越高
	 */
	@Override
	public int filterOrder() {
		return FilterConstants.SERVLET_DETECTION_FILTER_ORDER - 10;
	}
	
}
